<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>观察者模式</title>
</head>
<body>
    <script>
        class Publish{
        // 订阅者名单：记录所有订阅者
            constructor(){
                // { 类别:[具体的订阅者] }
                this.list = {}
            }
            // 添加订阅：类型、constructor订阅者的构造函数
            on(type,cons){
                // 类别存在则直接push，若不存在则赋值一个数组
                if(this.list[type] instanceof Array){
                    this.list[type].push(cons);
                }else{
                    this.list[type] = [cons];
                }
            }

            // 移除删除：根据对应的构造函数进行删除操作
            off(type,cons){
                if(!this.list[type]){
                    return false;
                }

                var idx = this.list[type].indexOf(cons);
                this.list[type].splice(idx,1);
            }

            // 触发：发布信息
            emit(type,msg){
                if(!this.list[type]){
                    return false;
                }
                !this.list[type].forEach(cons=>{
                    new cons(msg);
                })
            }
        }

        // 订阅者
        class Subscriber1{
            constructor(msg){
                this.msg = msg;
                this.name = '小明';
                console.log(this.name,this.msg);
            }
        }
        class Subscriber2{
            constructor(msg){
                this.msg = msg;
                this.name = '小红';
                console.log(this.name,this.msg);
            }
        }
        class Subscriber3{
            constructor(msg){
                this.msg = msg;
                this.name = '小梅';
                console.log(this.name,this.msg);
            }
        }

        var pub = new Publish();
        pub.on('boy',Subscriber1);
        pub.on('girl',Subscriber2);
        pub.on('girl',Subscriber3);
    </script>
</body>
</html>